package hclfns

import (
	"fmt"
	"github.com/ihaiker/tfwrapper/internal/errors"
	"github.com/ihaiker/tfwrapper/internal/shells"
	"os"
)

func runCommand(opts *FunctionOptions, args []string) (string, error) {
	if len(args) == 0 {
		return "", errors.WithStackTrace(fmt.Errorf("parameter to the run_cmd function"))
	}
	quiet := false
	if args[0] == "--quiet" {
		quiet = true
		args = args[1:]
	}
	cmd := shells.New(args[0], args[1:]...).WorkingDir(opts.WorkingDir)
	if !quiet {
		cmd.WithWriter(os.Stderr)
	}
	stdout, stderr, err := cmd.RunWithOutput()
	if err != nil {
		return "", fmt.Errorf(stderr)
	}
	return stdout, nil
}
